package org.karelun.whiteboard.ui.cdo;

import java.util.Collection;
import java.util.Iterator;

import org.eclipse.emf.cdo.CDOLock;
import org.eclipse.emf.cdo.util.CDOUtil;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.ui.IEditorPart;
import org.karelun.whiteboard.gef.ui.actions.SelectionAction;

/**
 * @Author: KarelunHuang
 * @Date: Jan 30, 2013
 **/
public class LockAction extends SelectionAction{

	public LockAction(IEditorPart editor) {
		super(editor);
		setId("lock");
		setText("lock");
	}
	
	@Override
	protected boolean calculateEnabled() {
		return isEditable()&&!isLocked();
	}
	
	private boolean isLocked() {
		Iterator<Object> iterator = getSelectedEditPartModels().iterator();
		if(!iterator.hasNext()){
			return true;
		}
		Object object = iterator.next();
		CDOLock cdoWriteLock = CDOUtil.getCDOObject((EObject)object).cdoWriteLock();
		return cdoWriteLock.isLocked()|| cdoWriteLock.isLockedByOthers();
	}

	@Override
	public void run() {
		Collection<Object> selectedModels = getSelectedEditPartModels();
		for(Object object: selectedModels){
			if(object instanceof EObject){
				CDOUtil.getCDOObject((EObject)object).cdoWriteLock().lock();
			}
		}
	}
}
